package com.tbit.uqbike.webmanager.controller;

import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.common.entity.vo.MainLogAuditBatchVo;
import com.tbit.uqbike.annos.OperateLog;
import com.tbit.uqbike.object.pojo.dto.WorkOrderLogQueryDTO;
import com.tbit.common.entity.pojo.dto.BarChartDispatchLogDTO;
import com.tbit.common.entity.pojo.vo.DateResult;
import com.tbit.uqbike.object.pojo.statistics.DispatchLog;
import com.tbit.uqbike.object.pojo.statistics.ExportPowerLog;
import com.tbit.common.entity.vo.MainLogAuditVo;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.uqbike.service.business.DispatchLogService;
import com.tbit.uqbike.service.business.PowerChangeMonitorConfigService;
import com.tbit.uqbike.webmanager.util.PowerLogExportUtil;
import com.tbit.uqbike.webmanager.util.ServletUtils;
import com.tbit.uqbike.webmanager.util.StringUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelWrapper;
import com.tbit.utils.Assert;
import com.tbit.utils.Excel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 调度记录
 *
 * @Author: chen
 * @Description: 调度统计
 * @Date: 创建于 11:45 2020/3/12
 */
@Slf4j
@Validated
@RestController
@RequestMapping(value = "/dispatchLogStat", produces = BaseController.MEDIA_JSON_UTF8)
public class DispatchLogController extends BaseController {
    @Autowired
    private DispatchLogService dispatchLogService;
    @Autowired
    private PowerChangeMonitorConfigService powerChangeMonitorConfigService;


    /**
     * 柱状图数据
     * @param barChartDispatchLogDTO 请求参数
     * @return JsonResult
     */
    @RequestMapping("/statisticsByTime")
    public JsonResult statisticsByTime(BarChartDispatchLogDTO barChartDispatchLogDTO) {
        Assert.notNulls("参数有误", barChartDispatchLogDTO.getAccountId(), barChartDispatchLogDTO.getStartTime(), barChartDispatchLogDTO.getEndTime());
        List<List<DateResult>> list = dispatchLogService.statisticsByTime(barChartDispatchLogDTO);
        return JsonResult.ok(list);
    }

    /**
     * 分页查询详细
     */
    @RequestMapping("/queryPage")
    public JsonResult queryPage(WorkOrderLogQueryDTO queryDTO) {
        queryDTO.selfCheck();
        queryDTO.buildDispatchSqlCondition(powerChangeMonitorConfigService::getById);
        Integer total = dispatchLogService.queryCount(queryDTO);
        if (total <= 0) {
            return JsonResult.ok(Collections.emptyList(), total);
        }
        List<DispatchLog> list = dispatchLogService.queryPage(queryDTO);
        return JsonResult.ok(list, total);
    }

    /**
     * 导出
     */
    @RequestMapping("/exportByTime")
    public void exportByTime(WorkOrderLogQueryDTO queryDTO, HttpServletResponse response) {
        queryDTO.selfCheck();
        queryDTO.buildDispatchSqlCondition(powerChangeMonitorConfigService::getById);
        Assert.notNull(queryDTO.getStartTime(), "ver.startTime.notNull");
        Assert.notNull(queryDTO.getEndTime(), "ver.endTime.notNull");
        RequestContext context = getLogin(ServletUtils.getRequest()).getContext();
        List<DispatchLog> list = dispatchLogService.exportByTime(queryDTO);
        List<String[]> exportList = PowerLogExportUtil.getExportContent(null, null, list, null, context);
        ExportExcelWrapper<String[]> export = new ExportExcelWrapper<>();
        export.exportExcel(context.getMessage("excel_head_dispatch"), context.getMessage("excel_head_dispatch"), null, exportList, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    /**
     * 调度总详情
     */
    @RequestMapping("/getByType")
    public JsonResult getByType(@NotNull(message = "ver.accountId.notNull") Integer accountId, Integer accountUserId, @NotNull(message = "ver.startTime.notNull") Long startTime, @RequestParam(required = false, value = "regionIds") String regionIds, @RequestParam(required = false, value = "type") Integer type,
                                @NotNull(message = "ver.endTime.notNull") Long endTime, @RequestParam(defaultValue = "10") Integer rowCount, @RequestParam(defaultValue = "1") Integer pageNO, @RequestParam(required = false, value = "sort") String sort, Integer machineType, HttpServletResponse response) {
        Assert.notNull(sort, "顺序标识不能为空");
        List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
        List<ExportPowerLog> list = dispatchLogService.getByType(accountId, accountUserId, startTime, endTime, rowCount, pageNO, regionIdList, type, machineType);
        Integer count = dispatchLogService.getByType(accountId, accountUserId, startTime, endTime, 0, 1, regionIdList, type, machineType).size();
        if ("asc".equals(sort)) {
            /**升序排列*/
            List<ExportPowerLog> ascendingList = list.stream().sorted(Comparator.comparing(ExportPowerLog::getTotal)).collect(Collectors.toList());
            return JsonResult.ok(ascendingList, count);
        } else if ("desc".equals(sort)) {
            /**降序排列*/
            List<ExportPowerLog> descendingList = list.stream().sorted(Comparator.comparing(ExportPowerLog::getTotal).reversed()).collect(Collectors.toList());
            JsonResult.ok(descendingList, count);
        }
        return JsonResult.ok(startPage(list), count);
    }

    @RequestMapping("/exportByTimeByRegionId")
    public void exportByTimeByRegionId(@NotNull(message = "ver.accountId.notNull") Integer accountId, Integer accountUserId, @NotNull(message = "ver.startTime.notNull") Long startTime, @RequestParam(required = false, value = "regionIds") String regionIds, @RequestParam(required = false, value = "type") Integer type,
                                       @NotNull(message = "ver.endTime.notNull") Long endTime, Integer machineType, HttpServletResponse response) {
        try {
            List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
            List<ExportPowerLog> list = dispatchLogService.getByType(accountId, accountUserId, startTime, endTime, 0, 1, regionIdList, type, machineType);
            List<String> cellNameList = new ArrayList<>();
            int row = 1;
            String fileName = "调度记录.xls";
            String title = "调度记录";
            HSSFWorkbook excel = null;
            if (type == 0) {
                cellNameList.add("手机号码");
                cellNameList.add("姓名");
                cellNameList.add("总次数");
                cellNameList.add("有效");
                cellNameList.add("无效");
                cellNameList.add("审核中");
                excel = Excel.createExcel(title, cellNameList);
                for (ExportPowerLog exportPowerLog : list) {
                    List<String> excelData = new ArrayList<>();
                    excelData.add(exportPowerLog.getPhone() + "");
                    excelData.add(exportPowerLog.getName() + "");
                    excelData.add(exportPowerLog.getTotal().toString());
                    excelData.add(exportPowerLog.getValid() + "");
                    excelData.add(exportPowerLog.getUnValid() + "");
                    excelData.add(exportPowerLog.getUnderReview() + "");
                    excel = Excel.createExcelData(excel, excelData, row);
                    row++;
                }
            } else if (type == 1) {
                cellNameList.add("分区名");
                cellNameList.add("总次数");
                cellNameList.add("有效");
                cellNameList.add("无效");
                cellNameList.add("审核中");
                excel = Excel.createExcel(title, cellNameList);
                for (ExportPowerLog exportPowerLog : list) {
                    List<String> excelData = new ArrayList<>();
                    excelData.add(exportPowerLog.getRegionName().toString());
                    excelData.add(exportPowerLog.getTotal().toString());
                    excelData.add(exportPowerLog.getValid() + "");
                    excelData.add(exportPowerLog.getUnValid() + "");
                    excelData.add(exportPowerLog.getUnderReview() + "");
                    excel = Excel.createExcelData(excel, excelData, row);
                    row++;
                }
            }
            OutputStream out = null;
            String headStr = "attachment; filename=\"" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + "\"";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            excel.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 审核操作
     */
    @RequestMapping("/auditOperation")
    @OperateLog(module = ModuleEnum.DISPATCHLOG, methods = MethodEnum.DISPATCHLOG_UPDATE)
    public JsonResult auditOperation(@Valid MainLogAuditVo vo) {
        LoginInfo login = getLogin(ServletUtils.getRequest());
        dispatchLogService.updateAudit(vo,login);
        return JsonResult.ok();
    }

    /**
     * 批量审核
     */
    @RequestMapping("/auditOperationBatch")
    @OperateLog(module = ModuleEnum.DISPATCHLOG, methods = MethodEnum.DISPATCHLOG_UPDATE_BATCH)
    public JsonResult auditOperationBatch(@Valid MainLogAuditBatchVo vo) {
        LoginInfo login = getLogin(ServletUtils.getRequest());
        dispatchLogService.auditOperationBatch(vo,login);
        return JsonResult.ok();
    }
}
